package com.zb.mail;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

//带图片的邮件
public class ImageMail {

    public static void main(String[] args) throws Exception {
        Properties properties = new Properties();
        properties.setProperty("mail.host", "smtp.qq.com");
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("594507903@qq.com", "wtacdribubspbdhh");
            }
        });
        session.setDebug(true);

        Transport transport = session.getTransport();
        transport.connect();

        //===============================只有信息内容与简单邮件不同================================//
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("594507903@qq.com"));
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("594507903@qq.com"));
        message.setSubject("带图片的邮件");

        MimeBodyPart image = new MimeBodyPart();
        DataHandler dataHandler = new DataHandler(new FileDataSource("/Users/juzi/Documents/idea-Workspace/MyResource/java-web-servlet/mail-java/邮件原理.png"));
        image.setDataHandler(dataHandler);
        image.setContentID("1.png");

        MimeBodyPart content = new MimeBodyPart();
        content.setContent("这是带图片<img src='cid:1.png' />的邮件", "text/html;charset=utf-8");

        MimeMultipart mimeMultipart = new MimeMultipart();
        mimeMultipart.addBodyPart(image);
        mimeMultipart.addBodyPart(content);
        mimeMultipart.setSubType("related");

        message.setContent(mimeMultipart);
        message.saveChanges();
        //===============================只有信息内容与简单邮件不同================================//

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

    }
}
